const {getAccountList, login, newAccount, updateAccountPassword, deleteAccount, getAccountDetail} = require('../controller/user')
const {SuccessModel, ErrorModel} = require('../model/response')
var express = require('express');
const {delStudentByUsername} = require("../controller/student");
const {delCoachByUsername} = require("../controller/coach");
var router = express.Router();

/**
 * 管理员路由操作
 * Login.vue：/login
 * User.vue: /list, /update, /del/:id
 * 前端路由index.js； /validate
 */
// 登录的验证(session是否含有用户名，跳转的路径是否与角色相同)
router.post('/validate', (req, res, next) => {
  let path = req.body.path.split('/')
  if (req.session.username) {
    if (path[1] !== req.session.rolename) {
      res.json(new ErrorModel('请求页面与角色不符，请先登录...'))
    } else {
      res.json(new SuccessModel())
    }
  } else {
    res.json(new ErrorModel('请先登录...'))
  }
})
// 账户登录
router.post('/login', (req, res, next) => {
  const result = login(req.body)
  return result.then(row => {
    if (row.username) {
      // 登录成功设置session，自动同步到redis
      req.session.username = row.username
      req.session.rolename = row.rolename
      res.json(new SuccessModel('登录成功'))
    } else {
      res.json(new ErrorModel("登陆失败"))
    }
  })
});
// 获取所有账户信息
router.get('/list', (req, res, next) => {
  const result = getAccountList()
  return result.then(rows => {
    res.json(new SuccessModel(rows))
  })
});
// 修改账户密码
router.post('/update', (req, res, next) => {
  const result = updateAccountPassword(req.body)
  return result.then(val => {
    if (val) {
      res.json(new SuccessModel('修改账户密码成功'))
    } else {
      res.json(new ErrorModel('修改账户密码失败'))
    }
  })
});
// 删除账户信息，删除对应学员或教练信息
router.post('/del/:id', async (req, res, next) => {
  const result = await deleteAccount(req.params.id)
  if (result) {
    if (req.body.rolename === 'student') {
      const StudentResult = await delStudentByUsername(req.body.identify)
      if (StudentResult) {
        res.json(new SuccessModel('删除账户成功'))
      }
    } else {
      const CoachResult = await delCoachByUsername(req.body.identify)
      if (CoachResult) {
        res.json(new SuccessModel('删除账户成功'))
      }
    }
  } else {
    res.json(new ErrorModel('删除账户失败'))
  }
});
/**
 * 学员、教练路由操作
 * Account.vue: /update
 * CoachAccount.vue: /detail
 * StudentAccount.vue: /detail
 */
// 获取账户详细信息
router.get('/detail', (req, res, next) => {
  const result = getAccountDetail(req.session.username)
  return result.then(row => {
    if (row.username) {
      res.json(new SuccessModel(row))
    } else {
      res.json(new ErrorModel('获取账户详细信息失败'))
    }
  })
})

// 添加学员或教练时，创建默认账户信息（未用到该路由）
router.post('/new', (req, res, next) => {
  const result = newAccount(req.body)
  return result.then(val => {
    if (val) {
      res.json(new SuccessModel(val))
    } else {
      res.json(new ErrorModel(val))
    }
  })
});
module.exports = router;
